package vodoo.tools;

import java.util.StringTokenizer;

public class InetTools {
	//--------------------------------------------------------- CONSTANTES --//
	//---------------------------------------------------------- ATTRIBUTS --//
	//------------------------------------------------------ CONSTRUCTEURS --//
	//----------------------------------------------------------- METHODES --//
	
	public static String ipToString(byte[] ip) {
		String result = "";
		
		for (int i = 0; i < ip.length; i++)
			result += (i == 0 ? "" : ".") + (ip[i] + 256) % 256;
		
		return result;
	}
	
	public static byte[] stringToIp(String ip) {
		StringTokenizer tokenizer = new StringTokenizer(ip, ".");
		byte[] result = new byte[tokenizer.countTokens()];
		
		for (int i = 0; i < result.length; i++)
		{
			result[i] = (byte)Integer.parseInt(tokenizer.nextToken());
		}
		
		return result;
	}
	
	public static boolean WellFormedIP( String IPtoCheck )
	{
		StringTokenizer eltIP = new StringTokenizer( IPtoCheck, "." );
		int elt = 0;
		
		for ( int i = 0 ; i < 4 ; ++i )
		{
			if( ! eltIP.hasMoreTokens() )
			{
				return false;
			} 
			
			try
			{
				elt = Integer.parseInt( eltIP.nextToken() );
			}
			catch ( NumberFormatException ex )
			{
				return false;
			}
			
			if( (elt < 0) || (elt > 255))
			{
				return false;
			}		
		}
		
		// On teste si le dernier n'est pas un 0 ou un 255
		if( (elt == 0) || (elt == 255) )
		{
			return false;
		}
		
		return true;
	}
	/**
	 * 
	 * @param portToCheck
	 * @return le port si c'est bon
	 * 			-1 si pas bon
	 */
	public static int WellFormedPort( String portToCheck )
	{
		int port = 0 ;
		try
		{
			port = Integer.parseInt( portToCheck );
		}
		catch( NumberFormatException ex )
		{
			return -1;
		}
		
		if( (port < 0) || (port > 65535)  )
		{
			return -1;
		}
		
		return port;
	}

	//--------------------------------------------------- METHODES PRIVEES --//
}
